package com;

import net.sf.json.JSONObject;

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Start {

    static URL loginURL;
    static URL signInURL;
    static URL planIdURL;

    static String Json;
    static String token;
    static String sign;
    static String userId;
    static String moguNo;

    static String accont = "";
    static String passwrod = "";
    static String State = "";
    static String address = "";
    static String country = "";
    static String province = "";
    static String planId = "";
    static String city = "";
    static String longitude = "";
    static String latitude = "";

    //签到使用的json
    static String SignInJson = "";

    //http请求头部信息。
    public final static String Accept_Language = "zh-CN,zh;q=0.8";
    public final static String user_agent_value = "Mozilla/5.0 (Linux; Android 7.0; HTC M9e Build/EZG0TF) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.1566.54 Mobile Safari/537.36";
    public final static String Content_Type = "application/json; charset=UTF-8";
    public final static String Host = "api.moguding.net:9000";
    public final static String Accept_Encoding = "";
    public final static String Cache_Control = "no-cache";

    //用于将程序运行过程中的信息输出到RunTimeLog.txt文件中 方便对异常就行追查
    static StringBuffer s = new StringBuffer();


    public static void main(String[] args) throws IOException {
        init();

        BufferedReader in = null;
        try {

            InputStreamReader isr = new InputStreamReader(new FileInputStream("src/MoGuDing.txt"), "UTF-8");
            in = new BufferedReader(isr);
//            in =new BufferedReader(new FileReader("src/MoGuDing.txt"),);
            String str = "";
            while ((str = in.readLine()) != null) {
                String[] split = str.split(":");
                try {

                    for (int i = 0; i < split.length; i++) {
                        System.out.print(split[i] + "-");
                        s.append(split[i] + "-");
                    }
                    Information(split[1],
                            split[2],
                            split[3],
                            split[4],
                            split[5],
                            split[6],
                            split[7],
                            split[8],
                            split[9]);
                    s.append("\n");

                } catch (Exception e) {
                    e.printStackTrace();
//                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//                    e.printStackTrace(new PrintWriter("Time : "+ df.format(new Date()) + "  账号："+accont +" Jons= " + Json));
                }

            }
            in.close();

            BufferedWriter out = new BufferedWriter(new FileWriter("RunTimeLogo" + day + ".txt"));
            out.write(s.toString());
            out.close();
        } catch (IOException e) {
            in.close();
            e.printStackTrace();
        }

    }


    /**
     * 初始化数据
     **/
    static Integer day = 0;

    public static void init() throws MalformedURLException {
        loginURL = new URL("https://api.moguding.net:9000/session/user/v1/login");
        signInURL = new URL("https://api.moguding.net:9000/attendence/clock/v2/save");
        planIdURL = new URL("https://api.moguding.net:9000/practice/plan/v3/getPlanByStu");
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("dd");
        day = Integer.valueOf(format.format(date));
    }


    public static void Information(String acconti, String password,
                                   String state, String addressi,
                                   String countryi, String provincei,
                                   String cityi, String longitudei,
                                   String latitudei) {
        accont = acconti;//账号
        passwrod = password;//密码
        State = state;//上班 or 下班
        address = addressi;//详细地址
        country = "中国";//国家
        province = provincei;//省份
        city = cityi;//城市
        longitude = longitudei;//经度
        latitude = latitudei;//纬度
        /**
         * 这个try代码块用于捕捉打卡时候的异常，并且可以让程序继续执行
         */
        try {
            SignIn();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static void SignIn() {
        s.append("LoginJson= " + "{\"password\":\"" + passwrod + "\", \"phone\":\"" + accont + "\", \"loginType\":\"android\",\"uuid\":\"\"}" + "\n");

        /**这条JSON是登陆时返回的JSON，用于初始化用户信息，例如：UserID PlanID Token*/

        Json = PostRequest(loginURL, "", "", "", "{\"password\":\"" + passwrod + "\",\"phone\":\"" + accont + "\",\"loginType\":\"android\",\"uuid\":\"\"}");

        s.append("LoginReturnJson = " + Json + "\n");

        getUserId();

        getToken();

        getPlanIdSign();

        getPlanId();


        getSign();

        /**这条JSon是用于发送签到请求的*/
        SignInJson = "{\"country\":\"" + country + "\"," +
                "\"address\":\"" + address + "\"," +
                "\"province\":\"" + province + "\"," +
                "\"city\":\"" + city + "\"," +
                "\"latitude\":\"" + latitude + "\"," +
                "\"description\":\"\"," +
                "\"planId\":\"" + planId + "\"," +
                "\"type\":\"" + State + "\"," +
                "\"device\":\"Android\"," +
                "\"longitude\":\"" + longitude + "\"" +
                "}";

        s.append("SignInJson = " + SignInJson + "\n");

        String loginReturn = "";

        try {

            loginReturn = PostRequest(signInURL, token, sign, "student", SignInJson);

            s.append("SignInJsonReturn = " + loginReturn + "\n");

        } catch (Exception e) {

            s.append("SignInJsonReturn = 签到时发生异常 未能签到成功 初步判断可能是网络异常导致的 \n");

            e.printStackTrace();
        }


    }


    public static String PostRequest(URL Url, String token, String sign, String roleKey, String jsonStr) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) Url.openConnection();
            conn.setRequestMethod("POST");

            //发送POST请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);

            conn.setRequestProperty("Host", Host);
            conn.setRequestProperty("Accept-Language", Accept_Language);
            conn.setRequestProperty("User-Agent", user_agent_value);
            conn.setRequestProperty("Sign", sign);
            conn.setRequestProperty("Authorization", token);
            conn.setRequestProperty("roleKey", roleKey);
            conn.setRequestProperty("Content-Type", Content_Type);
            conn.setRequestProperty("Accept-Encoding", Accept_Encoding);
            conn.setRequestProperty("Cache-Control", Cache_Control);
            //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream());

            out.write(jsonStr);
            out.flush();
            out.close();
            //取得输入流，并使用Reader读取
            if (200 == conn.getResponseCode()) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
            } else {

                s.append("ResponseCode is an error code:" + conn.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        return result.toString();
    }

    public static void getToken() {
        token = JSONObject.fromObject(Json).getJSONObject("data").getString("token");
        s.append("token = " + token + "\n");
    }

    public static void getUserId() {
        userId = JSONObject.fromObject(Json).getJSONObject("data").getString("userId");
        s.append("UserID = " + userId + "\n");

    }

    public static void getmoGuNo() {
        moguNo = JSONObject.fromObject(Json).getJSONObject("data").getString("moguNo");
        s.append("moguNo = " + moguNo + "\n");
    }

    public static void getPlanIdSign() {
        String str = userId + "student" + "3478cbbc33f84bd00d75d7dfa69e0daa";
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            // 一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方）
            sign = new BigInteger(1, md.digest()).toString(16);
            s.append("planID = " + sign + "\n");
            planId = sign;
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void getPlanId() {
        Json = PostRequest(planIdURL, token, sign, "student", "{\"state\":\"\"}");
        planId = JSONObject.fromObject(Json).getJSONArray("data").getJSONObject(0).getString("planId");
        s.append("planId = " + planId + "\n");

    }

    public static void getSign() {
        //这里的计划id需更改 自行抓包
        String str = "Android" + State + planId + userId + address + "3478cbbc33f84bd00d75d7dfa69e0daa";
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            // 一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方）
            sign = new BigInteger(1, md.digest()).toString(16);
            s.append("sign = " + sign + "\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}